package com.hitgo.soccer.handler;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hitgo.soccer.config.PropsConfig;
import com.hitgo.soccer.core.FBError;
import com.hitgo.soccer.core.Props;
import com.hitgo.soccer.core.Team;
import com.hitgo.soccer.database.PropsDAO;
import com.hitgo.soccer.database.TeamDAO;

public class PropsHandler extends BaseHandler
{
	private static BaseHandler instance = null;
	
	public static BaseHandler getInstance()
	{
		if(instance == null)
			instance = new PropsHandler();
		return instance;
	}

	@Override
	public void cmdHandler(int cmd, HttpServletRequest req,	HttpServletResponse res)
	{
		res.setContentType("text/plain");
		String strCmd = req.getParameter("fbCmd");
		String strParams = req.getParameter("fbParams");
		
		int nCmd = Integer.parseInt(strCmd);

		switch(nCmd)
		{
		case Commands.PROPS_BUY:
			buyPropos(res, strParams);
			break;
		case Commands.PROPS_USE:
			break;
		default:
			break;
		}
	}
	

	private int buyPropos(HttpServletResponse res, String strParams)
	{
		String[] saParams = strParams.split(Commands.PARAMS_SEPARATOR);
		Long lUserID = Long.parseLong(saParams[0]);
		int nPropID = Integer.parseInt(saParams[1]);
		int nPropCount = Integer.parseInt(saParams[2]);
		PropsConfig pConfig = PropsConfig.getPropsConfig(nPropID);
		if(pConfig == null)
			return FBError.ERROR_PROPS_INVALID_ID;
		
		Team team = TeamDAO.getTeam(lUserID);
		
		int nNeedMoney = pConfig.buy_money * nPropCount;
		if((pConfig.cash_type == 1 && nNeedMoney > team.getvMoney())
				|| nNeedMoney > team.getrMoney())
		{
			//	没有足够的钱
			return FBError.ERROR_NO_ENOUGH_MONEY;
		}
		
		Props pExist = null;
		ArrayList<Props> ap = PropsDAO.getProps(lUserID, nPropID);
		
		for(Props p:ap)
		{
			int nPackCount = p.getCount() + nPropCount;
			if(nPackCount <= pConfig.max_package)
			{
				//加到某一个包上
				pExist = p;
				break;
			}
		}

		boolean isNewPack = false;
		if(pExist == null)
		{
			// 判断背包 数量
			if(PropsDAO.getPackNum(lUserID) >= team.getPackCount())
			{
				// 背包满了
				return FBError.ERROR_PROPS_PACK_FULL;
			}
			isNewPack = true;
			pExist = new Props();
		}
		
		if(pConfig.cash_type == 1)
		{
			team.addvMoney(nNeedMoney);
		}
		else
		{
			team.addrMoney(nNeedMoney);
		}
		
		if(isNewPack == true)
		{
			PropsDAO.insertProps(pExist);
		}
		else
		{
			PropsDAO.updateProps(pExist);
		}
		
		TeamDAO.updateTeamMoney(team);
		
		return FBError.SUCCESS;
	}

}